package com.example.lsrsbackend.controller;

import com.example.lsrsbackend.model.Student;
import com.example.lsrsbackend.service.impl.StudentServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class StudentController {

    @Autowired
    private StudentServiceImpl studentService;

    @PostMapping("/login")
    public String login(@RequestBody Student student) {
        boolean success = studentService.login(student);
        if (success) {
            return "Login successful";
        } else {
            return "Login failed";
        }
    }

//    @PostMapping("/login")
//    public ResponseEntity<?> login(@RequestBody Student student) {
//        boolean success = studentService.login(student);
//        if (success) {
//            return ResponseEntity.ok().body("Login successful");
//        } else {
//            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Login failed");
//        }
//    }

    @PostMapping("/register")
    public String register(@RequestBody Student student) {
        studentService.register(student);
        return "Registration successful";
    }

    //修改密码
    /*
    常见方法
    1  简单修改密码（不校验）
    2  安全方法（对原密码进行校验）
    3  路径参数传递的方式

    此处暂时使用第一种！！！
    * */
    @PostMapping("/change-pw")
    public Map<String,Object> changePassword(@RequestBody Map<String,String>  request){  //Map<String, String> 表示接收的 JSON 数据中，键和值都是字符串类型
        Map<String,Object> response = new HashMap<>();

        String username = request.get("username");
        String newPassword = request.get("newPassword");
        if (username == null || newPassword == null) {
            response.put("success", false);
            response.put("message", "用户名和新密码不能为空");
            return response;
        }

        boolean result = studentService.changePassword(username, newPassword);
        response.put("success", result);
        response.put("message", result ? "密码修改成功" : "密码修改失败");

        return response;
    }
    //通过username查找student完整信息返回
    @GetMapping("/get-info")
    public Student getStudentInfo(@RequestParam String username) {
        return studentService.getStudentInfo(username);
    }

    //修改个人信息  使用PATCH方法 + 部分更新策略，路径参数+请求参数
    /*ikm
    该步骤需要前端精准将  修改的数据！！！   传给后端，不要盲目封装到一块 发给后端，部分更新策略！！！
    * */

    @PatchMapping("/update-info")
    public Map<String, Object> UpadateStudentInfo(@RequestParam String username
            ,@RequestBody Map<String,Object>  request) { //map<string object>适用于更多格式
        Map<String, Object> response = new HashMap<>();
        try{
            //调用service进行部分更新
            boolean result = studentService.partialupdate(username, request);
            response.put("success", result);
            response.put("message", result ? "个人信息修改成功" : "个人信息修改失败");
            response.put("updatedFields", request.keySet()); // 返回被更新的字段列表
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "更新异常: " + e.getMessage());
        }

        return response;
    }

    //获取全部students信息 列表形式返回
    @GetMapping("/get-all")
    public List<Student> getAllStudents() {
        return studentService.getAllStudents();
    }

    // 添加用户（管理员功能）
    @PostMapping("/add")   //！！！添加功能有问题 后边字段插不进去
    public ResponseEntity<Map<String, Object>> addStudent(@RequestBody Student student) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 检查用户名是否已存在
            Student existingStudent = studentService.getStudentInfo(student.getUsername());
            if (existingStudent != null) {
                response.put("success", false);
                response.put("message", "用户名已存在");
                return ResponseEntity.badRequest().body(response);
            }

            // 设置默认密码（建议在注册时要求设置密码，这里使用默认密码）
            if (student.getPassword() == null || student.getPassword().trim().isEmpty()) {
                student.setPassword("123456"); // 默认密码，建议要求前端传入
            }

            // 调用注册服务
            studentService.register(student);

            response.put("success", true);
            response.put("message", "用户添加成功");
            response.put("username", student.getUsername());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "添加用户失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 冻结功能
    @PostMapping("/freeze/{username}")
    public ResponseEntity<Map<String, Object>> freezeStudent(@PathVariable String username) {
        Map<String, Object> res = new HashMap<>();
        String status = studentService.getStudentStatus(username);
        if (status == null) {
            res.put("success", false);
            res.put("message", "用户不存在");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(res);
        }
        if (status == "frozen") {
            res.put("success", false);
            res.put("message", "用户已处于冻结状态");
            return ResponseEntity.badRequest().body(res);
        }
        int rows = studentService.freezeStudent(username);
        res.put("success", rows > 0);
        res.put("message", rows > 0 ? "冻结成功" : "冻结失败");
        return ResponseEntity.ok(res);
    }

    //解冻功能
    @PostMapping("/unfreeze/{username}")
    public ResponseEntity<Map<String, Object>> unfreezeStudent(@PathVariable String username) {
        Map<String, Object> res = new HashMap<>();
        String status = studentService.getStudentStatus(username);
        if (status == null) {
            res.put("success", false);
            res.put("message", "用户不存在");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(res);
        }
        if (status == "active") {
            res.put("success", false);
            res.put("message", "用户已处于正常状态");
            return ResponseEntity.badRequest().body(res);
        }
        int rows = studentService.unfreezeStudent(username);
        res.put("success", rows > 0);
        res.put("message", rows > 0 ? "解冻成功" : "解冻失败");
        return ResponseEntity.ok(res);
    }
    // 删除用户（管理员功能）
    @DeleteMapping("/delete/{username}")
    public ResponseEntity<Map<String, Object>> deleteStudent(@PathVariable String username) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 检查用户是否存在
            Student existingStudent = studentService.getStudentInfo(username);
            if (existingStudent == null) {
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }

            // 执行删除操作
            boolean result = studentService.deleteStudent(username);
            if (result) {
                response.put("success", true);
                response.put("message", "用户删除成功");
                response.put("deletedUsername", username);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "用户删除失败");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "删除用户异常: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }






}